/*
** server.c -- a datagram sockets "server" demo
** From http://www.beej.us/guide/bgnet/output/html/singlepage/bgnet.html
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

#include "unreliable.h"
#include "shared.h"


#define MAXBUFLEN 100

int main(void)
{
    int sockfd;
    struct addrinfo hints, *servinfo, *p;
    int rv;
    int numbytes;
    struct sockaddr_storage their_addr;
    char buf[MAXBUFLEN];
    socklen_t addr_len;
    char s[INET6_ADDRSTRLEN];
    char receivedMsg[2048];

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_DGRAM;
    hints.ai_flags = AI_PASSIVE; // use my IP

    if ((rv = getaddrinfo(NULL, SERVERPORT, &hints, &servinfo)) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
        return 1;
    }

    // loop through all the results and bind to the first we can
    for(p = servinfo; p != NULL; p = p->ai_next) {
        if ((sockfd = socket(p->ai_family, p->ai_socktype,
			     p->ai_protocol)) == -1) {
            perror("server: socket");
            continue;
        }

        if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
            close(sockfd);
            perror("server: bind");
            continue;
        }

        break;
    }

    if (p == NULL) {
        fprintf(stderr, "server: failed to bind socket\n");
        return 2;
    }

    freeaddrinfo(servinfo);


    P("\n(SVR) Listening...");
    RCConnection con = Listen(sockfd, (struct sockaddr*)&their_addr);
    if(con.State == CONNECTED){
        P("(SVR) Connected!\n");
    }
    else
        P("(SVR) Failed...\n");


    int currChar = 0;
    RCPacket packet = {0};

	printf("Waiting for something to read...\n");
    currChar = 0;

    if(ReceivePacType(&con, &packet, SYN)){
        con.SeqNum = packet.SeqNum;
        Send(&con, ACK, '\0');

        while(1){
            Recieve(&con, &packet);
            con.SeqNum = packet.SeqNum;

            if(packet.Flags == 0){
                receivedMsg[currChar++] = packet.Character;
                printf("***** Received character: %c *****\n", packet.Character);
                Send(&con, ACK, '\0'); // acknowledge the packet
            }
            else if(packet.Flags == FIN){
                Send(&con, ACK, '\0'); // acknowledge the end of the message
                receivedMsg[currChar] = '\0';
                break;
            }
        }

        printf("ENTIRE MESSAGE: %s\n", receivedMsg);
    }

    close(sockfd);
    printf("Connection is now closed\n");
    return 0;
}

